import serial
# todo 0x20 bug
history_label = 0
# 目前暂定dict保存10组数据0-9
history_dict = {}
# 使用0x99当成测试传输整数的命令


def pack1(a_int, a_command):
    # time 3,11
    data = hex(a_int)
    req = ""
    if len(data) % 2 == 1:
        temp = data[2::]
        data = "0x0" + temp
    data = data[2::]
    for i in range(0, len(data) - 1, 2):
        temp = "0x" + data[i:i + 2]
        req += temp
    data = req
    # todo 暂定command长度就是1
    length = hex(data.count("x") + a_command.count("x"))
    if len(length)==3:
        length = "0x0" + length[-1]
    print("data", data)
    print("a_command",a_command)
    # 注意，上面这个长度只能是1
    verify_code = hex(a_int + eval(a_command))
    verify_code = "0x" + verify_code[-2::]
    temp = ("0xFE" + length + data + a_command + verify_code + "0xFF").upper().replace("X", "x")
    return temp


def send_raw(str1, ser, history_label):
    """
    将0x转化成杠x进行发送
    # todo 尚未完成
    :param str1: 待发送的串
    :param ser:
    :param history_label:
    :return:
    """
    ser.write(str1.encode("utf-8"))
    print(str1)
    history_dict[history_label % 10] = str1
    history_label += 1


def init(portx1):
    # todo 这个函数可能要拆开
    portx = portx1
    bps = 115200
    timex = 5
    ser = serial.Serial(portx, bps, timeout=timex)
    return ser


def send(data, command):
    """
    :param data: 数据
    :param command: 要求0x格式的字符串指令
    :return: 执行状态：
        1000 一切正常
        1001 传进去的应该是整数，但是不是
        1002 没匹配到合适的指令
    """
    # todo 向字典形式适配
    if command == "0x99":
        if type(data) != int:
            return 1001
        to_send = pack1(data, command)
        send_raw(to_send, ser, history_label)
    else:
        return 1002


ser = init("COM5")
print(send(1234, "0x99"))
x = input("inputing...")
#ser.close()  # 测试用功能
# todo 需要手动close
